package com.dudu.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dudu.access.RedisUtil;

/**
 * 生成验证码
 * 
 * @author zx
 *
 */
public class CaptchaAction extends HttpServlet {

	public static final String VALIDATE_CODE_KEY = "ValidateCode";

	private static final long serialVersionUID = 1L;

	private Font mFont = new Font("Times New Roman", Font.PLAIN, 20);

	public static int contNo = 4; 

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CaptchaAction() {
		super();
	}

	Color getRanColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);//
		int g = fc + random.nextInt(bc - fc);//
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setHeader("Pragm", "No-cache");
		response.setHeader("Cache-control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		int width = 75, height = 22;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		Random random = new Random();
		// Color c = new Color(200,255,0,0);
		g.setColor(getRanColor(200, 250)); // 填充颜色getRanColor(200,250)
		g.fillRect(1, 1, width - 1, height - 1);
		g.setColor(new Color(102, 102, 102));// 边框的颜色
		g.drawRect(0, 0, width - 1, height - 1);
		g.setFont(mFont);
		g.setColor(getRanColor(160, 200));
		String sRand = "";
		for (int i = 0; i < contNo; i++) { // 一共显示6个数
			int temp = random.nextInt(9);
			sRand += String.valueOf(temp);
			g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(String.valueOf(temp), 15 * i + 10, 16); // string, x, y
		}
		String uuid = request.getParameter("uuid");
		RedisUtil.setString(VALIDATE_CODE_KEY + uuid, 30 * 60, sRand);
		g.dispose();
		ImageIO.write(image, "jpeg", response.getOutputStream());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
